package com.english.numbers;

import java.util.ArrayList;
import java.util.Random;

import com.english.numbers.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

public class Training extends Activity implements OnClickListener {

    String correctAnswerNumber = "";
	String currentCorrectAnswer="";
    ArrayList<String> currentExpression = null;
    CountDownTimer timer;
    boolean demo = false;

    
    final Integer[] levelWords = {20,20,20,20};
    final Integer[] secToThink = {8,12,15,20};
    final Integer maxLevel = 4;
    final Integer rPoint = 4;
    final Integer wPoint = 1;
    ArrayList<Integer> records = new ArrayList<Integer>();
    Integer currentLevel = 0;
    Integer wordCount = 0;
    Integer wrongCount = 0;
    Integer points = 0;
    boolean gameFinished = false;
    boolean exit = false;

 
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        initiateLayout();
        setNewExpression();
        updateMainView();
    }
    
    public void initiateLayout(){
        SharedPreferences settings = getSharedPreferences("Com.numbers.learn", 0);
        this.currentLevel = settings.getInt("level", 0);
        this.wordCount = settings.getInt("wordCount", 0);
        this.wrongCount = settings.getInt("wrongCount", 0);
        this.points = settings.getInt("points", 0);
        this.demo = settings.getBoolean("demo", false);
        String name = "record"+currentLevel.toString();
        this.records.add(settings.getInt(name+"1",0 ));
        this.records.add(settings.getInt(name+"2",0 ));
        this.records.add(settings.getInt(name+"3",0 ));
        this.records.add(settings.getInt(name+"4",0 ));
        this.records.add(settings.getInt(name+"5",0 ));
        ProgressBar bar = (ProgressBar) findViewById(R.id.main_scoresProgress);
        bar.setProgressDrawable(getResources().getDrawable(R.drawable.progressbar));
        
    	Button possible1 = (Button) findViewById(R.id.main_possible1);
    	Button possible2 = (Button) findViewById(R.id.main_possible2);
    	Button possible3 = (Button) findViewById(R.id.main_possible3);
    	Button possible4 = (Button) findViewById(R.id.main_possible4);
    	Button backInMenu = (Button) findViewById(R.id.main_backInMenu);
     	
         possible1.setOnClickListener(this);
         possible2.setOnClickListener(this);
         possible3.setOnClickListener(this);
         possible4.setOnClickListener(this);
         backInMenu.setOnClickListener(this);
         

    }
    
    private void checkDemo(){
        if((this.demo == true)&&(this.currentLevel>0)){
        	AlertDialog.Builder builder = new AlertDialog.Builder(this);
         	builder.setMessage(getResources().getString(R.string.demoText))
             .setCancelable(false)
             .setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
                 public void onClick(DialogInterface dialog, int id) {
                    if(timer!=null)
                  	   timer.cancel();
 			    	Intent mIntent = new Intent(Training.this, Start.class);
			    	Training.this.startActivity(mIntent);
	            	Training.this.finish();
                 }
             });
     		AlertDialog alert = builder.create();
     		alert.show();
         }
    }
    
    @Override
	public void onClick(View v) {
		if(timer!=null)
			timer.cancel();
		Button clickedButton = (Button) v;
		Button backinMenuButton = (Button) findViewById(R.id.main_backInMenu);
			if(clickedButton.equals(backinMenuButton)){
		    	Intent myIntent = new Intent(Training.this, Start.class);
		    	Training.this.startActivity(myIntent);
            	Training.this.finish();
		    	return;
			}
			if(clickedButton.getText().equals(this.currentCorrectAnswer)){
				increasePoints();
				if(!this.gameFinished){
					setNewExpression();
					updateMainView();
				}
			}
			else{
			    decreasePoints();
			    saveAll();
		    	Intent myIntent = new Intent(Training.this, Mistake.class);
		    	Training.this.startActivity(myIntent);
            	Training.this.finish();
			}
	}
	
    private void decreasePoints(){
       	this.points-=this.wPoint;
       	this.wrongCount++;
       	if(this.points<0)
        		this.points=0;
       	{

       	}

    }
    
    private void increasePoints(){
    	this.points+=this.rPoint;
    	if((this.wordCount-this.wrongCount)>=this.levelWords[this.currentLevel])
    		levelUp();
    }
    
    private void levelUp(){
    	stopLearning();
    }
    
    
    private void stopLearning(){
    	if(this.timer!=null)
    		timer.cancel();
    	this.gameFinished = true;
    	if(this.points > this.records.get(4)){
    		/*
    		 * new record
    		 */
    		for(int i=0;i<5;i++){
    			if(this.points==this.records.get(i)){
    				break;
    			}
    			if(this.points>this.records.get(i)){
    				this.records.add(i, this.points);
    				break;
    			}
    		}
    		if(this.records.size()>5)
    			this.records.remove(5);
    		saveAll();
    		/*
    		 * TODO showing dialog with record
    		 */
    		final CharSequence[] items ;
    		if(this.currentLevel == this.maxLevel-1){
    			items = new CharSequence[4];
    			items[0] = getString(R.string.startFirstLevel);
    			items[1] = getString(R.string.repeatThisLevel);
    			items[2] = getString(R.string.lookRecords);
    			items[3] = getString(R.string.finishGame);
//    			this.currentLevel=0;
    		}
    		else{
    			items = new CharSequence[4];
    			items[0] = getString(R.string.startNextLevel);
    			items[1] = getString(R.string.repeatThisLevel);
    			items[2] = getString(R.string.lookRecords);
    			items[3] = getString(R.string.finishGame);
//    			this.currentLevel++;
    		}

    		AlertDialog.Builder builder = new AlertDialog.Builder(this);
    		builder.setTitle("You have set new record " + this.points.toString());
    		builder.setItems(items, new DialogInterface.OnClickListener() {
    		    public void onClick(DialogInterface dialog, int item) {
    		        //Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
    		    	switch(item ){
    		    	case 0:
    		    		currentLevel++;
    		    		points = 0;
    		    		wordCount = 0;
    		    		wrongCount = 0;
    		    		gameFinished = false;
   // 		    		initiateLayout();
    		            setNewExpression();
    		            updateMainView();
    		    	break;
    		    	case 1:
    		    		points = 0;
    		    		wordCount = 0;
    		    		wrongCount = 0;
    		    		gameFinished = false;
 //   		    		initiateLayout();
    		            setNewExpression();
    		            updateMainView();
    		        break;
    		    	case 2:
    	            	Intent myIntent = new Intent(Training.this, Results.class);
    	            	Training.this.startActivity(myIntent);
    	            	Training.this.finish();
    		    	break;
    		    	case 3:
    			    	Intent mIntent = new Intent(Training.this, Start.class);
    			    	Training.this.startActivity(mIntent);
    	            	Training.this.finish();
    		    	break;
    		    		
    		    		
    		    	}
    		    }
    		});
    		AlertDialog alert = builder.create();
    		alert.show();
    	}else{
    		final CharSequence[] items ;
    		if(this.currentLevel == this.maxLevel-1){
    			items = new CharSequence[4];
    			items[0] = getString(R.string.startFirstLevel);
    			items[1] = getString(R.string.repeatThisLevel);
    			items[2] = getString(R.string.lookRecords);
    			items[3] = getString(R.string.finishGame);
    		}
    		else{
    			items = new CharSequence[4];
    			items[0] = getString(R.string.startNextLevel);
    			items[1] = getString(R.string.repeatThisLevel);
    			items[2] = getString(R.string.lookRecords);
    			items[3] = getString(R.string.finishGame);
    		}

    		AlertDialog.Builder builder = new AlertDialog.Builder(this);
    		builder.setTitle("You have finished level with result " + this.points);
    		builder.setItems(items, new DialogInterface.OnClickListener() {
    		    public void onClick(DialogInterface dialog, int item) {
    		        //Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
    		    	switch(item ){
    		    	case 0:
    		    		currentLevel++;
    		    		points = 0;
    		    		wordCount = 0;
    		    		wrongCount = 0;
    		    		gameFinished = false;
//    		    		initiateLayout();
    		            setNewExpression();
    		            updateMainView();
    		    	break;
    		    	case 1:
    		    		points = 0;
    		    		wordCount = 0;
    		    		wrongCount = 0;
    		    		gameFinished = false;
//    		    		initiateLayout();
    		            setNewExpression();
    		            updateMainView();
    		        break;
    		    	case 2:
    	            	Intent myIntent = new Intent(Training.this, Results.class);
    	            	Training.this.startActivity(myIntent);
    	            	Training.this.finish();
    		    	break;
    		    	case 3:
    			    	Intent mIntent = new Intent(Training.this, Start.class);
    			    	Training.this.startActivity(mIntent);
    	            	Training.this.finish();
    		    	break;
    		    	}
    		    }
    		});
    		AlertDialog alert = builder.create();
    		alert.show();
    	}
   }
    
    private void updateMainView(){
        TextView scoreField = (TextView) findViewById(R.id.main_scores);
     	TextView mistakeField = (TextView) findViewById(R.id.main_mistakes);
     	TextView numbersLeftField = (TextView) findViewById(R.id.main_numbersLeft);
      	ProgressBar scoresProgress =  (ProgressBar) findViewById(R.id.main_scoresProgress);
        
      	scoreField.setText(this.points.toString());
        mistakeField.setText(this.wrongCount.toString());
        numbersLeftField.setText(Integer.toString(this.levelWords[this.currentLevel]-this.wordCount+this.wrongCount+1));
    	scoresProgress.setMax(this.levelWords[this.currentLevel]);
    	scoresProgress.setProgress(this.wordCount-this.wrongCount-1);
    }

    
    /*
     * setting the new View if pressed button was with wrong value
     * shows correct answer and the translation of numbers used in the expression
     * sets listener for button continueTraining
     * the listener is current class
     */
    private void setNewExpression(){
    	checkDemo();
    	if(this.currentLevel>=this.maxLevel)
    		this.currentLevel = 0;
    	wordCount++;
    	String[] numbers = getResources().getStringArray(R.array.textNumbers);
    	
    	TextView main_expression = (TextView) findViewById(R.id.main_expression);
    	Button possible1 = (Button) findViewById(R.id.main_possible1);
    	Button possible2 = (Button) findViewById(R.id.main_possible2);
    	Button possible3 = (Button) findViewById(R.id.main_possible3);
    	Button possible4 = (Button) findViewById(R.id.main_possible4);
   
    	if(timer!=null)
    		timer.cancel();
        Expression expression = new Expression();
        expression.setLevel(currentLevel);
        ArrayList<String> newExpression = expression.getExpression();
        this.currentExpression = newExpression;
        
        int n1 = Integer.parseInt(newExpression.get(1));
        int n2 = Integer.parseInt(newExpression.get(2));
        int c = Integer.parseInt(newExpression.get(3));
        
        
        main_expression.setText(numbers[n1]+" " + newExpression.get(0) +" "+ numbers[n2] +" =");

        this.correctAnswerNumber = newExpression.get(3);
        this.currentCorrectAnswer = numbers[c];
        
        /*
         * Put correct answer on random position
         */
        Random rand = new Random();
        int correct = rand.nextInt(4);
        String rightAnswer = newExpression.get(3);
        newExpression.set(3, newExpression.get(correct+3));
        newExpression.set(correct+3, rightAnswer);
        
        /*
         * set values to the buttons
         */
        int p1 = Integer.parseInt(newExpression.get(3));
        int p2 = Integer.parseInt(newExpression.get(4));
        int p3 = Integer.parseInt(newExpression.get(5));
        int p4 = Integer.parseInt(newExpression.get(6));

        
        possible1.setText(numbers[p1]);
        possible2.setText(numbers[p2]);
        possible3.setText(numbers[p3]);
        possible4.setText(numbers[p4]);
        
        timer = new CountDownTimer(this.secToThink[this.currentLevel]*1000, 1000) {
        	public int wordNumber = wordCount;
        	public void onTick(long millisUntilFinished) {
        		if(wordCount == wordNumber){
        			TextView timeLeft = (TextView) findViewById(R.id.main_timeLeft);
        			timeLeft.setText(Integer.toString(((int)millisUntilFinished/1000)-1));
        			updateMainView();
        		}
        	}
        	public void onFinish() {
        		if((wordCount == wordNumber)&&(!gameFinished))
        			decreasePoints();
        			saveAll();
        			Intent myIntent = new Intent(Training.this, Mistake.class);
        			Training.this.startActivity(myIntent);
                	Training.this.finish();
        	}
        	};
        timer.start();
    }
   
    private void saveAll(){
           // We need an Editor object to make preference changes.
        // All objects are from android.context.Context
        SharedPreferences settings = getSharedPreferences("Com.numbers.learn", 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putInt("level", this.currentLevel);
        editor.putInt("wordCount", this.wordCount);
        editor.putInt("wrongCount", this.wrongCount);
        editor.putInt("points", this.points);
        editor.putBoolean("gameFinished", this.gameFinished);

    	  String[] numbers = getResources().getStringArray(R.array.textNumbers);
        int n1 = Integer.parseInt(this.currentExpression.get(1));
        int n2 = Integer.parseInt(this.currentExpression.get(2));
        
        editor.putString("correctAnswerNumber", this.correctAnswerNumber);
        editor.putString("currentCorrectAnswer", this.currentCorrectAnswer);
        editor.putString("number1", this.currentExpression.get(1));
        editor.putString("number2", this.currentExpression.get(2));
        editor.putString("number1Text", numbers[n1]);
        editor.putString("number2Text", numbers[n2]);
        editor.putString("expression", numbers[n1]+" " + this.currentExpression.get(0) +" "+ numbers[n2] +" = " + this.currentCorrectAnswer);
        
        String name = "record"+currentLevel.toString();
        editor.putInt(name+"1", this.records.get(0));
        editor.putInt(name+"2", this.records.get(1));
        editor.putInt(name+"3", this.records.get(2));
        editor.putInt(name+"4", this.records.get(3));
        editor.putInt(name+"5", this.records.get(4));
        // Commit the edits!
        editor.commit();
    }
    
    @Override
    protected void onStop(){
       super.onStop();
       if(timer!=null)
    	   timer.cancel();
       saveAll();
    }

}
